" vim: ft=vim ts=4 sw=4 et

" Plugins:
let s:autoload_directory = expand('<sfile>:p:h')
let s:vimfiles = fnamemodify(s:autoload_directory, ':p:h:h')
let g:vimfiles = get(g:, 'vimfiles', s:vimfiles)
if !filereadable(globpath(g:vimfiles, 'plugin.vim'))
	let g:vimfiles = s:vimfiles
endif
let g:plugin_root = fnamemodify(globpath(substitute(g:vimfiles, '\', '/', 'g'), 'pack/github.com/opt/'), ':p')

function! plugin#list() abort
    let g:plugin_directory_list = globpath(g:plugin_root, '*', v:false, v:true)
    let g:plugin_list = map(copy(g:plugin_directory_list), 'fnamemodify(v:val, ":t")')
    let g:plugin_name_list = map(copy(g:plugin_list), 'substitute(v:val, "-", "_", "g")')
    return g:plugin_list
endfunction


function! plugin#command() abort
    command! -nargs=1 -complete=customlist,plugin#complete LoadPlugin call plugin#load(<args>)
endfunction

function! plugin#config(plugin_name) abort
    try
        return plugin#{a:plugin_name}#config()
    catch /^Vim\%((\a\+)\)\=:E117/	 " 捕获所有的 Vim 错误
        " echom 'plugin#' . a:plugin_name . '#config() is not found.'
    catch /^Vim\%((\a\+)\)\=:E/	 " 捕获所有的 Vim 错误
        echom v:exception 
    endtry
endfunction

function! plugin#init(plugin_name) abort
    try
        return plugin#{a:plugin_name}#init()
    catch /^Vim\%((\a\+)\)\=:E117/	 " 捕获所有的 Vim 错误
        " echom 'plugin#' . a:plugin_name . '#init() is not found.'
    catch /^Vim\%((\a\+)\)\=:E/	 " 捕获所有的 Vim 错误
        echom v:exception 
    endtry
endfunction

function! plugin#load(plugin) abort
    let g:disabled_plugins = get(g:, 'disabled_plugins', [])
    if index(g:disabled_plugins, a:plugin) < 0
        let plugin_name_sans_ext = fnamemodify(a:plugin, ':r')
        let plugin_name = substitute(plugin_name_sans_ext, "-", "_", "g")
        try
            " echom 'calling plugin#config("' . plugin_name . '")'
            call plugin#config(plugin_name)
            let ok = plugin#{plugin_name}#load()
            if ok 
                " echom 'loading ' . plugin_name . ' sucecssfully.'
            endif
            return plugin#init(plugin_name) 
        catch /^Vim\%((\a\+)\)\=:E117/	 " 捕获所有的 Vim 错误
            " echom 'plugin#' . plugin_name . '#load() is not found.'
            packadd a:plugin
            return plugin#init(plugin_name) 
        catch /^Vim\%((\a\+)\)\=:E/	 " 捕获所有的 Vim 错误
            echom 'plugin#' . plugin_name . '#load() is failed.'
            echom v:exception 
            execute("packadd " . a:plugin)
        endtry
    else
        echom a:plugin . " has been disabled."
    endif
endfunction

function! plugin#complete(arglead, cmdline, curpos) abort
    return get(g:, 'plugin_list', plugin#list())
endfunction

function! plugin#after() abort
	if plugin#load('gruvbox')
		colorscheme gruvbox
    endif
endfunction

function! plugin#loadall() abort
    call map(copy(plugin#list()), 'plugin#load(v:val)')
    call plugin#after() 
endfunction

